import json
import time

from django.core.cache import cache
from django.forms import model_to_dict
from django.http import FileResponse
from django.views.decorators.cache import cache_page
from django.conf import settings
from apps.demomanager import service as DemoServer
from apps.usermanager import service as UserServer
from comment.errorcode import *
from .models import *
import logging
from utils.esutils import DemoEs as EStools

es_tools = EStools()


# error
def error_ret(error, message):
    """
    错误返回
    :param error:
    :param message:
    :return:
    """
    return [error, message, None]


def demo_main(request,params=None):
    """
    普通首页
    :param request:
    :return:
    """
    data = {}
    cls_id = params.get("cls_id")
    size = params.get("size")
    page = params.get("page")
    scene = params.get("scene")
    supreme = params.get("supreme")
    if scene == -1:
        demos = DemoServer.demo_list_classes(cls_id, size, page, supreme)
    else:
        demos = DemoServer.demo_list_scene(cls_id, scene, size, page, supreme)
    if isinstance(demos, ErrorMsg):
        return demos.msg
    # count = len(demos)
    data["demos"] = demos
    data["url"] = "/demomanager/demo?active=read"
    # data["count"] = count
    return [CREATE_OK, "查询成功", data, 1]


def demo_menus(request,params=None):
    """
    主页标题
    :param request:
    :return:
    """
    now_time = int(time.time()) // 1000
    cache_data = cache.get(now_time)
    if cache_data:
        return [SELECT_OK, "查询成功", cache_data, 1]
    data = {}
    classes = DemoServer.democlasses_list()
    user_top = UserServer.user_top3()
    demo_top = DemoServer.demo_top10()
    sence = DemoServer.scene_list()
    data["menu"] = classes
    data["userTop"] = user_top
    data["demoTop"] = demo_top
    data["sence"] = sence
    cache.set(now_time, data, 17 * 16)
    return [SELECT_OK, "查询成功", data, 1]


def demo_read(request,params=None):
    """
    档案阅读
    :param request:
    :return:
    """
    data = {}
    demo_id = params.get("demo_id")
    author_id = request.session.get("author_id")
    user_id = request.session.get("user_id") if settings.DEBUG == False else params.get("user_id")
    demo_info = DemoServer.demo_info(demo_id)
    if demo_info is None:
        return ErrorMsg(SELECT_ERROR, "查询失败").msg
    files = DemoServer.demofile_list_demo(demo_id)
    collect = DemoServer.collect_info_user(user_id, demo_id)
    data["demoInfo"] = demo_info
    data["files"] = files if len(files) > 0 else None
    data["collected"] = collect
    # 如果阅读者不是作者，阅读次数加一
    if author_id != user_id:
        DemoServer.demo_read_add(demo_id)
    return [SELECT_OK, "查询成功", data, 1]


def demo_create(request,params=None):
    """
    档案创建
    :param request:
    :return:
    """
    data = {}
    indexchar = params.get("indexchar")
    product = params.get("product")
    title = params.get("title")
    remarks = params.get("remarks")
    content = params.get("content")
    author_id = params.get("author_id")
    classes_id = params.get("classes_id")
    scene_id = params.get("scene_id")
    files = params.get("files")
    demo_result = DemoServer.demo_add(product=product, title=title,
                                      remarks=remarks, content=content, author_id=author_id, classes_id=classes_id,
                                      scene_id=scene_id)
    if isinstance(demo_result, ErrorMsg):
        return demo_result.msg
    files_result = DemoServer.files_bind_demo(demo_result, files.split(";") if isinstance(files, str) else None)
    if isinstance(files_result, ErrorMsg):
        return files_result.msg
    indexchar_result = DemoServer.indexchar_add(indexchar.split(":") if isinstance(files, str) else None, demo_result)
    if isinstance(indexchar_result, ErrorMsg):
        return indexchar_result.msg
    es_result = es_tools.create(demo_result, indexchar.split(":") if isinstance(files, str) else None)
    if es_result == 0:
        return ErrorMsg(SERVER_EMPTY).msg
    # data["demo"] = model_to_dict(demo_result)
    return [SELECT_OK, "创建成功", None, 1]


def demo_edit_ready(request,params=None):
    """
    编辑加载
    :param request:
    :return:
    """
    demo_id = params.get("demo_id")
    demo_result = DemoServer.demo_info(demo_id, get_all=False,
                                       params=["title", "remarks", "scene_id", "content", "classes_id", "product"])
    if isinstance(demo_result, ErrorMsg):
        return demo_result.msg
    classes_result = DemoServer.democlasses_list(get_parent=False, get_url=False)
    if isinstance(classes_result, ErrorMsg):
        return classes_result.msg
    scene_result = DemoServer.scene_list(get_urls=False)
    if isinstance(scene_result, ErrorMsg):
        return scene_result.msg
    indexchar_result = DemoServer.indexchar_list(demo_id)
    data = {}
    data["scene"] = scene_result
    data["classes"] = classes_result
    data["demo"] = demo_result
    data['indexchar'] = indexchar_result
    return [SELECT_OK, "场景加载", data, 1]


def demo_edit_update(request,params=None):
    """
    编辑上传
    :param request:
    :return:
    """
    data = {}
    id = params.get("id")
    indexchar = params.get("indexchar")
    product = params.get("product")
    title = params.get("title")
    remarks = params.get("remarks")
    content = params.get("content")
    author_id = params.get("author_id")
    classes_id = params.get("classes_id")
    scene_id = params.get("scene_id")
    files_add_id = params.get("files_add_id")
    files_del_id = params.get("files_del_id")
    demo_result = DemoServer.demo_update(id, product=product, title=title,
                                         remarks=remarks, content=content, author_id=author_id, classes_id=classes_id,
                                         scene_id=scene_id)
    if isinstance(demo_result, ErrorMsg):
        return demo_result.msg
    files_result = DemoServer.files_bind_demo(demo_result,
                                              files_del_id.split(";") if isinstance(files_del_id, str) else None)
    if isinstance(files_result, ErrorMsg):
        return files_result.msg
    files_result = DemoServer.files_bind_demo(demo_result,
                                              files_add_id.split(";") if isinstance(files_del_id, str) else None)
    if isinstance(files_result, ErrorMsg):
        return files_result.msg
    indexchar_result = DemoServer.indexchar_add(indexchar.split(";") if isinstance(indexchar, str) else None,
                                                demo_result)
    if isinstance(indexchar_result, ErrorMsg):
        return indexchar_result.msg
    es_result = es_tools.update(demo_result, indexchar.split(";") if isinstance(indexchar, str) else None)
    if es_result == 0:
        return ErrorMsg(SERVER_EMPTY).msg
    data["demo"] = model_to_dict(demo_result)
    return [SELECT_OK, "修改成功", data, 1]


def demo_superme(request,params=None):
    """
    精品
    :param request:
    :return:
    """
    data = {}
    demo_id = params.get("demo_id")
    superme_result = DemoServer.demo_superme(demo_id)
    if isinstance(superme_result,ErrorMsg):
        return superme_result.msg
    data["result"] = superme_result
    if superme_result:
        return [SELECT_OK, "精品设置成功", data, 1]
    else:
        return [SELECT_OK, "取消精品成功", data, 1]


def user_search(request,params=None):
    """
    人物搜索
    :param request:
    :return:
    """
    # 搜索结果
    froms = params.get("froms")
    keyword = params.get("keyword")
    
    if not all([froms, keyword]):
        return ErrorMsg(PARAMS_EMPTY).msg
    
    info_list = es_tools.search(keyword, froms)
    if info_list is None:
        return ErrorMsg(SELECT_ERROR).msg
    # 加入数据表段count
    for info in info_list:
        try:
            UserServer.user_demos_num(info.get("id"))
        except Exception as e:
            info["count"] = 0
            continue
    
    return [SELECT_OK, "查询成功", info_list, 1]


def demo_file_update(request,params=None):
    """
    文件上传
    :param request:
    :return:
    """
    file = request.FILES.get("file")
    file_result = DemoServer.demofile_add(file)
    if isinstance(file_result, ErrorMsg):
        return file_result.msg
    data = dict()
    data["file"] = file_result
    return [CREATE_OK, "成功", data, 1]


def demo_file_download(request,params=None):
    """
    文件下载
    :return:
    """
    file = open('/home/amarsoft/download/example.tar.gz', 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="example.tar.gz"'
    return response


def collect_demo(request,params=None):
    """
    收藏collect成功
    :param request:
    :return:
    """
    user_id = request.session.get("user_id") if settings.DEBUG==False else params.get("user_id")
    demo_id = params.get("demo_id")
    delete = params.get("delete")
    if not all([user_id, demo_id]):
        return ErrorMsg(PARAMS_EMPTY).msg
    if delete:
        result = DemoServer.collect_del(demo_id, user_id)
    else:
        result = DemoServer.collect_add(demo_id, user_id)
    if isinstance(result, ErrorMsg):
        return result.msg
    result = DemoServer.demo_collect_update(demo_id, delete)
    if isinstance(result, ErrorMsg):
        return result.msg
    if delete:
        message = "取消收藏成功"
    else:
        message = "收藏成功"
    return [UPDATE_OK, message, None, 1]
